package com.awardsystem.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.awardsystem.Service.*;
import com.awardsystem.Utils.ColumnTitleMap;
import com.awardsystem.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class PatentController {
    @Autowired
    PatentService patentService;
    @Autowired
    UserService userService;
    @Autowired
    AchievementService achievementService;
    @Autowired
    ExportDataService exportDataService;
    @GetMapping("/getAllPatent")
    public JSONObject getAllPatent(){
        JSONObject ret=new JSONObject();
        List<Patent> patentList=patentService.findAll();
        List<Map<String,Object>> result=new ArrayList<>();
        for(Patent patent:patentList){
            Map<String,Object> info=new HashMap<>();
            List<Achievement> achievements=patent.getAchievements();
            info.put("achievements",achievements);
            info.put("id",patent.getId());
            info.put("name",patent.getName());
            info.put("number",patent.getNumber());
            info.put("url",patent.getUrl());
            info.put("type",patent.getType());
            info.put("applyTime",patent.getApplyTime());
            info.put("authTime",patent.getAuthTime());
            info.put("authors",patent.getAuthors());
            result.add(info);
        }
        ret.put("patent_list",result);

        ret.put("success",true);
        ret.put("exc","success");
        return ret;
    }

    @PostMapping("/addPatent")
    public JSONObject addPatent(@RequestBody JSONObject params) throws ParseException {
        JSONObject ret=new JSONObject();
        String name=params.getString("name");

        if(patentService.findByNameEquals(name)!=null){
            ret.put("success",false);
            ret.put("exc","存在同名");
            return ret;
        }
        else{

            String type=params.getString("type");
            String url=params.getString("certificate");
            LocalDate apply_date = LocalDate.parse(params.getString("apply_date"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate auth_date = LocalDate.parse(params.getString("auth_date"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            JSONArray author_array=params.getJSONArray("authors");
            List<User> authorList=author_array.toJavaList(User.class);
            List<User> author_list=new ArrayList<>();
            for(User user:authorList){
                User user0=userService.findUserByNumber(user.getNumber());
                if(user0==null){
                    ret.put("success",false);
                    ret.put("exc","不存在作者");
                    return ret;
                }
                author_list.add(user0);
            }


            Patent patent=new Patent();
            patent.setName(name);
            url="http://8.140.124.245:10000/resources/"+url;
            patent.setUrl(url);
            patent.setAuthors(authorList);
            patent.setApplyTime(apply_date);
            patent.setAuthTime(auth_date);
            patent.setAuthors(author_list);
            patent.setType(type);
            patentService.save(patent);
            ret.put("success",true);
            ret.put("exc","success");
            return ret;
        }
    }

    @PostMapping("/patent/search")
    public JSONObject findProject(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        String name=params.getString("keyword");
        List<Patent> patentList=patentService.findByNameContains(name);//粗查询
        ret.put("success",true);
        ret.put("exc","success");
        ret.put("patent_list",patentList);
        return ret;
    }

    @DeleteMapping("/patent/{id}")
    public JSONObject deleteSCI(@PathVariable("id")Integer id){
        JSONObject ret=new JSONObject();
        Patent patent=patentService.findById(id);

        if(patent==null){
            ret.put("success",false);
            ret.put("exc","不存在");
        }
        else{
            patentService.delete(patent);
            ret.put("success",true);
            ret.put("exc","success");
        }
        return ret;
    }

    @PutMapping("/patent/{id}")
    public JSONObject updatePatent(@PathVariable("id")Integer id,@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        Patent patent=patentService.findById(id);
        String name=params.getString("name");
        String url=params.getString("certificate");
        LocalDate apply_date = LocalDate.parse(params.getString("apply_date"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate auth_date = LocalDate.parse(params.getString("auth_date"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        JSONArray author_array=params.getJSONArray("authors");
        List<User> authorList=author_array.toJavaList(User.class);
        List<User> author_list=new ArrayList<>();
        JSONArray achievements=params.getJSONArray("achievements");
        List<Achievement> achievementList=achievements.toJavaList(Achievement.class);
        JSONArray projects=params.getJSONArray("projects");
        List<Project> projectList=projects.toJavaList(Project.class);
        for(User user:authorList){
            User user0=userService.findUserByNumber(user.getNumber());
            if(user0==null){
                ret.put("success",false);
                ret.put("exc","不存在作者");
                return ret;
            }
            author_list.add(user0);
        }
        System.out.println(authorList);
        if(patent==null){
            ret.put("success",false);
            ret.put("exc","不存在");
        }
        else{
            patent.setName(name);
            url="http://8.140.124.245:10000/resources/"+url;
            patent.setUrl(url);
            patent.setAuthors(authorList);
            patent.setApplyTime(apply_date);
            patent.setAuthTime(auth_date);
            patent.setAuthors(author_list);
            patent.setProjectList(projectList);
            patent.setAchievements(achievementList);
            patentService.save(patent);
            ret.put("success",true);
            ret.put("exc","success");
        }
        return ret;
    }

    @PostMapping("/patent/excel")
    public void patentExcel(HttpServletResponse response,@RequestBody JSONObject params){
        List<Map<String ,Object>> sciList=new ArrayList<>();
        List<Patent> patents=new ArrayList<>();
        List<Integer> idList=params.getObject("idList",List.class);
        for(Integer id:idList){
            Patent patent=patentService.findById(id);
            patents.add(patent);
        }
        for(Patent patent:patents){
            HashMap<String,Object> info=new HashMap<>();
            info.put("patent_id",patent.getId());
            info.put("apply_date",patent.getApplyTime().toString());
            info.put("auth_date",patent.getAuthTime().toString());
            info.put("name",patent.getName());
            info.put("type",patent.getType());
            String url=patent.getUrl();
            info.put("url",url);
            List<Achievement> achievements=patent.getAchievements();
            int num=1;
            StringBuilder achievementInfo= new StringBuilder();
            for(Achievement achievement:achievements){
                String achievementName=Integer.toString(num);
                achievementName+=".";
                achievementName+=achievement.getName();
                achievementInfo.append(achievementName);
                achievementInfo.append(';');
                num++;
            }
            info.put("achievements", achievementInfo.toString());
            List<User> authors=patent.getAuthors();
            num=1;
            StringBuilder authorInfo=new StringBuilder();
            for(User author:authors){
                String authorName=Integer.toString(num);
                authorName+=".";
                authorName+=author.getPersonName();
                authorInfo.append(authorName);
                authorInfo.append(';');
                num++;
            }
            info.put("authors",authorInfo.toString());
            List<Project> projects=patent.getProjectList();
            num=1;
            StringBuilder projectInfo=new StringBuilder();
            for(Project project:projects){
                String projectName=Integer.toString(num);
                projectName+=".";
                projectName+=project.getName();
                projectInfo.append(projectName);
                projectInfo.append(';');
                num++;
            }
            info.put("projects",projectInfo.toString());
            sciList.add(info);
        }
        ArrayList<String> titleKeyList= new ColumnTitleMap("patent").getTitleKeyList();
        Map<String, String> titleMap = new ColumnTitleMap("patent").getColumnTitleMap();
        exportDataService.exportDataToEx(response, titleKeyList, titleMap, sciList);
    }

}
